// ==UserScript==
// @name         打印标签
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @updateURL    https://gitee.com/great-pacey/tampermonkey/raw/master/print.walmart.user.js
// @match        https://seller.walmart.com/wfsLite/send-inventory/shipment/details
// @icon         https://www.google.com/s2/favicons?domain=walmart.com
// @require      https://code.jquery.com/jquery-3.6.0.min.js
// @grant        GM_registerMenuCommand
// @grant        unsafeWindow
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';
    GM_registerMenuCommand('print', main)

    function download(upc) {
    upc = upc.length === 14 ? upc.slice(2) : upc;

    const param = {
        payload: {
            "labelFormat": "PDF",
            "labelTemplateId": "1_1inch_2inch_Thermal_Label",
            items: [{ gtin: '00' + upc }]
        }
    };
    return new Promise(resolve => {
        $.ajax({
            type: "POST", contentType: "application/json; charset=utf-8",
            url: "https://seller.walmart.com/api/gateway/wmtfs-lite/itemLabel/download",
            data: JSON.stringify(param),
            xhrFields: {
                responseType: 'blob'
            },
            success: function (data) {
                var fileName = `00${upc}.pdf`;
                if ('download' in document.createElement('a')) {
                    //非IE下载
                    const elink = document.createElement('a');
                    elink.download = fileName;
                    elink.style.display = 'none';
                    elink.href = URL.createObjectURL(data);
                    document.body.appendChild(elink);
                    elink.click();
                    URL.revokeObjectURL(elink.href);
                    document.body.removeChild(elink);
                } else {
                    navigator.msSaveBlob(blob, fileName);
                }
                resolve()
            }
        });
    })
}

function downloadInBulk(upcs) {
    (async function loop() {
        if (upcs.length) {
            await download(upcs.shift());
            loop()
        }
    })();
}

function getGtins() {
    return [].slice.call(document.querySelectorAll('th+td')).map(i=>i.innerText)
}

function main() {
    downloadInBulk(getGtins())
}
})();